import asyncio
import os
from typing import List, Dict, Any, Optional
from datetime import datetime
import json

from ..models.kimi_client import KimiClient
from ..tools.search_tool import WebSearchTool
from ..tools.report_generator import ReportGenerator
from ..utils.logger import setup_logger

class ResearchAgent:
    """
    智能研究报告生成智能体
    
    主要功能：
    1. 根据用户输入主题自动搜索相关资料
    2. 整理和分析搜索到的信息
    3. 使用Kimi大模型生成结构化的研究报告
    4. 支持多种报告格式和自定义配置
    """
    
    def __init__(
        self,
        kimi_client: Optional[KimiClient] = None,
        search_tool: Optional[WebSearchTool] = None,
        report_generator: Optional[ReportGenerator] = None
    ):
        self.kimi_client = kimi_client or KimiClient()
        self.search_tool = search_tool or WebSearchTool()
        self.report_generator = report_generator or ReportGenerator(self.kimi_client)
        self.logger = setup_logger(__name__)
        
        # 配置参数
        self.config = {
            "max_search_results": int(os.getenv("MAX_SEARCH_RESULTS", 10)),
            "search_engine": os.getenv("SEARCH_ENGINE", "duckduckgo"),
            "report_language": os.getenv("REPORT_LANGUAGE", "zh"),
            "report_format": os.getenv("REPORT_FORMAT", "markdown")
        }
    
    async def generate_research_report(
        self,
        topic: str,
        report_type: str = "comprehensive",
        custom_sections: Optional[List[str]] = None,
        max_search_results: Optional[int] = None,
        save_to_file: bool = True
    ) -> Dict[str, Any]:
        """
        生成完整的研究报告
        
        Args:
            topic: 研究主题
            report_type: 报告类型 ("comprehensive", "brief", "technical")
            custom_sections: 自定义章节列表
            max_search_results: 最大搜索结果数量
            save_to_file: 是否保存到文件
            
        Returns:
            包含完整报告信息的字典
        """
        self.logger.info(f"开始生成关于{topic}的研究报告")
        
        start_time = datetime.now()
        
        try:
            # 1. 搜索相关资料
            search_results = await self._search_materials(
                topic, max_search_results
            )
            
            # 2. 生成报告
            report = await self._create_report(
                topic, search_results, report_type, custom_sections
            )
            
            # 3. 保存报告（如果要求）
            if save_to_file:
                file_path = await self.report_generator.save_report(report)
                report["file_path"] = file_path
            
            # 4. 记录统计信息
            end_time = datetime.now()
            duration = (end_time - start_time).total_seconds()
            
            report["statistics"] = {
                "search_results_count": len(search_results),
                "generation_time_seconds": duration,
                "total_sources": len(set([r.get("source", "unknown") for r in search_results]))
            }
            
            self.logger.info(f"研究报告生成完成，用时{duration:.2f}秒")
            
            return report
            
        except Exception as e:
            self.logger.error(f"生成研究报告失败: {e}")
            raise
    
    async def _search_materials(
        self,
        topic: str,
        max_results: Optional[int] = None
    ) -> List[Dict[str, Any]]:
        """
        搜索相关资料
        
        Args:
            topic: 研究主题
            max_results: 最大结果数量
            
        Returns:
            搜索结果列表
        """
        max_results = max_results or self.config["max_search_results"]
        
        self.logger.info(f"开始搜索关于{topic}的资料...")
        
        # 使用搜索工具搜索
        async with self.search_tool as search:
            search_results = await search.search_and_fetch(
                topic, max_results
            )
        
        self.logger.info(f"搜索完成，找到{len(search_results)}个结果")
        
        # 过滤和验证结果
        valid_results = []
        for result in search_results:
            if result.get("content") and len(result.get("content", "")) > 50:
                valid_results.append(result)
        
        self.logger.info(f"有效搜索结果: {len(valid_results)}个")
        
        return valid_results
    
    async def _create_report(
        self,
        topic: str,
        search_results: List[Dict[str, Any]],
        report_type: str,
        custom_sections: Optional[List[str]]
    ) -> Dict[str, Any]:
        """
        创建研究报告
        
        Args:
            topic: 研究主题
            search_results: 搜索结果
            report_type: 报告类型
            custom_sections: 自定义章节
            
        Returns:
            报告字典
        """
        return await self.report_generator.generate_research_report(
            topic=topic,
            search_results=search_results,
            report_type=report_type,
            custom_sections=custom_sections
        )
    
    async def quick_search_summary(
        self, topic: str, max_results: int = 5
    ) -> Dict[str, Any]:
        """
        快速搜索并生成摘要
        
        Args:
            topic: 搜索主题
            max_results: 最大结果数
            
        Returns:
            摘要信息
        """
        self.logger.info(f"快速搜索摘要: {topic}")
        
        search_results = await self._search_materials(topic, max_results)
        
        # 生成简要摘要
        summary_prompt = f"""
        基于以下搜索结果，为"{topic}"主题生成一个简洁的摘要：
        
        """
        
        for i, result in enumerate(search_results[:3], 1):
            summary_prompt += f"{i}. {result.get('title', '')}: {result.get('snippet', '')}\n"
        
        summary_prompt += f"\n请生成一个200字以内的中文摘要，突出最重要的信息。"
        
        messages = [{"role": "user", "content": summary_prompt}]
        summary = await self.kimi_client.chat_completions(messages, max_tokens=300)
        
        return {
            "topic": topic,
            "summary": summary,
            "sources_count": len(search_results),
            "sources": [
                {
                    "title": r.get("title"),
                    "url": r.get("url"),
                    "source": r.get("source")
                }
                for r in search_results
            ]
        }
    
    async def analyze_trends(
        self, topics: List[str]
    ) -> Dict[str, Any]:
        """
        分析多个相关主题的趋势
        
        Args:
            topics: 主题列表
            
        Returns:
            趋势分析报告
        """
        self.logger.info(f"开始分析趋势: {topics}")
        
        results = {}
        
        for topic in topics:
            try:
                summary = await self.quick_search_summary(topic, max_results=3)
                results[topic] = summary
            except Exception as e:
                self.logger.error(f"分析主题{topic}失败: {e}")
                results[topic] = {"error": str(e)}
        
        # 生成趋势分析
        trend_prompt = f"""
        基于以下主题的研究摘要，提供一个综合的趋势分析：
        
        {json.dumps(results, ensure_ascii=False, indent=2)}
        
        请分析：
        1. 这些主题之间的关联性
        2. 共同的发展趋势
        3. 未来的发展方向
        4. 潜在的机会和挑战
        
        请用中文回答，限制在500字以内。
        """
        
        messages = [{"role": "user", "content": trend_prompt}]
        trend_analysis = await self.kimi_client.chat_completions(messages, max_tokens=800)
        
        return {
            "topics": topics,
            "individual_results": results,
            "trend_analysis": trend_analysis,
            "generated_at": datetime.now().isoformat()
        }
    
    def get_config(self) -> Dict[str, Any]:
        """
        获取当前配置
        
        Returns:
            配置字典
        """
        return self.config.copy()
    
    def update_config(self, **kwargs) -> None:
        """
        更新配置
        
        Args:
            **kwargs: 配置参数
        """
        self.config.update(kwargs)
        self.logger.info(f"配置已更新: {kwargs}")

    async def interactive_mode(self) -> None:
        """
        交互模式，允许用户实时输入主题
        """
        print("🤖 智能研究报告生成器")
        print("=" * 50)
        print("输入主题开始研究，输入 'quit' 退出，输入 'help' 获取帮助")
        
        while True:
            try:
                topic = input("\n请输入研究主题: ").strip()
                
                if not topic:
                    continue
                
                if topic.lower() == 'quit':
                    print("感谢使用！再见！")
                    break
                
                if topic.lower() == 'help':
                    self._show_help()
                    continue
                
                if topic.lower() == 'config':
                    print(f"当前配置: {self.get_config()}")
                    continue
                
                # 询问报告类型
                print("\n选择报告类型:")
                print("1. 综合报告 (comprehensive)")
                print("2. 简要报告 (brief)")
                print("3. 技术报告 (technical)")
                
                choice = input("请选择 (1-3，默认1): ").strip()
                report_types = {
                    "1": "comprehensive",
                    "2": "brief",
                    "3": "technical"
                }
                report_type = report_types.get(choice, "comprehensive")
                
                # 生成报告
                print(f"\n正在生成{topic}的{report_type}报告...")
                report = await self.generate_research_report(
                    topic=topic,
                    report_type=report_type,
                    save_to_file=True
                )
                
                print(f"✅ 报告生成完成！")
                print(f"📄 文件路径: {report.get('file_path', '未保存')}")
                print(f"📊 统计信息: {report.get('statistics', {})}")
                
            except KeyboardInterrupt:
                print("\n操作已取消")
                break
            except Exception as e:
                print(f"❌ 执行失败: {e}")
                self.logger.error(f"交互模式错误: {e}")
    
    def _show_help(self) -> None:
        """
        显示帮助信息
        """
        print("""
帮助信息:
- 输入主题名称开始研究
- 'quit' - 退出程序
- 'help' - 显示此帮助
- 'config' - 显示当前配置

支持的报告类型:
- comprehensive: 综合详细报告
- brief: 简要报告
- technical: 技术详细报告
        """)